package com.zw.weiyi.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;

import com.zw.weiyi.adapter.CallAdapter;
import com.zw.weiyi.avtivity.CallInfo;
import com.zw.weiyi.enety.Call;
import com.zw.weiyi.phonesms.R;
import com.zw.weiyi.util.CallUtil;
import com.zw.weiyi.util.FiledDraw;
import com.zw.weiyi.util.MessageUtil;
import com.zw.weiyi.util.PhoneUtil;

/**
 * 通话记录 
 * @author Striver_zw
 *  Date 2014-12-9
 */
@SuppressLint("ValidFragment")
public class CallFragment extends Fragment implements OnItemLongClickListener {

	private ListView callListView;
	private AsyncQueryHandler asyncQuery;// 异步查询数据库类对象
	private CallAdapter adapter;
	private List<Call> callList;

	private Context context;
	private View view;// 缓存页面

	public CallFragment(Context context) {
		this.context = context;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.call_fragment, container, false);
		}
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);// 先移除
		}
		// 初始化
		initview(view);
		return view;
	}

	// 初始化
	public void initview(View view) {
		callListView = (ListView) view.findViewById(R.id.call_log_list);
		asyncQuery = new MyAsyncQueryHandler(context.getContentResolver());

		// 设置自定义控件
		FiledDraw.setDraw(context, callListView);
		init();
		// 设置监听事件
		callListView.setOnItemLongClickListener(this);

	}

	private void init() {
		Uri uri = android.provider.CallLog.Calls.CONTENT_URI;
		// 查询的列
		String[] projection = { CallLog.Calls.DATE, // 日期
				CallLog.Calls.NUMBER, // 号码
				CallLog.Calls.TYPE, // 类型
				CallLog.Calls.CACHED_NAME, // 名字
				CallLog.Calls._ID, // id
		};
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				CallLog.Calls.DEFAULT_SORT_ORDER);
	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {
				callList = new ArrayList<Call>();
				SimpleDateFormat sfd = new SimpleDateFormat("MM-dd HH:mm");// 时间格式
				Date date;
				cursor.moveToFirst(); // 游标移动到第一项
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					date = new Date(cursor.getLong(cursor
							.getColumnIndex(CallLog.Calls.DATE)));
					String number = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.NUMBER));
					int type = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls.TYPE));
					String cachedName = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.CACHED_NAME));// 缓存的名称与电话号码，如果它的存在
					int id = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls._ID));

					Call call = new Call();
					call.setId(id);
					call.setNumber(number);
					call.setName(cachedName);
					if (null == cachedName || "".equals(cachedName)) {
						call.setName(number);
					}
					call.setType(type);
					call.setDate(sfd.format(date));

					callList.add(call);
				}
				if (callList.size() > 0) {
					setAdapter(callList);
				}
			}
			super.onQueryComplete(token, cookie, cursor);
		}
	}

	private void setAdapter(List<Call> call) {
		adapter = new CallAdapter(context, call);
		callListView.setAdapter(adapter);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view,
			final int position, long id) {
		final Call call = callList.get(position);
		new AlertDialog.Builder(context)
				.setTitle("操作")
				.setItems(R.array.black_options,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (which == 0) {//
									PhoneUtil.phoneNumber(context, call.getNumber());							
								} else if (which == 1) {//详细信息
									 Intent intent = new Intent(context,CallInfo.class);
									 intent.putExtra("name",call.getName());
									 intent.putExtra("number",call.getNumber());
									 context.startActivity(intent);
								} else if (which == 2) {// 删除
									CallUtil.deleteCall(context, call.getType()+ "", call.getNumber());
									Toast.makeText(context, "删除成功", 1000).show();
									callList.remove(position);
									adapter.notifyDataSetChanged();
								}
							}
						}).show();
		return false;
	}
}
